package Demo1_10;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-01-10
 * Time:19:26
 */
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class KthToLast {
    public int kthToLast(ListNode head, int k) {
        if (head == null) {
            return -1;  // 这里可以根据实际情况定义返回值，比如抛出异常等，表示输入链表为空不符合要求
        }
        ListNode fast = head;
        ListNode slow = head;
        // 快指针先走k步
        for (int i = 0; i < k; i++) {
            if (fast == null) {
                return -1;  // 如果k大于链表长度，返回相应标识，也可做其他处理比如抛出异常
            }
            fast = fast.next;
        }
        // 快慢指针同时移动，直到快指针到达链表末尾
        while (fast!= null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow.val;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        KthToLast kthToLast = new KthToLast();
        int result = kthToLast.kthToLast(head, 2);
        System.out.println("倒数第2个节点的值为: " + result);
    }
}
